import {
  getNewCartGoods,
  mergeCartapi,
  findCartapi,
  insertCart,
  deleteCartapi,
  updateCartapi,
  checkAllCartapi
} from '@/apis/cart'
// 购物车模块
export default {
  namespaced: true,
  state () {
    return {
      // 购物车商品列表
      list: []
    }
  },
  getters: {
    // 有效商品列表
    validList (state, getter) {
      // console.log(state.list)
      // console.log(getter)
      return state.list.filter((item) => item.stock > 0 && item.isEffective)
      // return []
    },
    // 有效商品件数
    validTotal (state, getters) {
      return getters.validList.reduce((p, c) => p + c.count, 0)
    },
    // 有效商品总金额
    validAmount (state, getters) {
      return (
        getters.validList.reduce((p, c) => p + c.nowPrice * 100 * c.count, 0) /
        100
      )
    },
    // 无效商品列表
    invalidList (state) {
      return state.list.filter(
        (goods) => goods.stock <= 0 || !goods.isEffective
      )
    },
    // 已选商品列表
    selectedList (state, getters) {
      return getters.validList.filter((item) => item.selected)
    },
    // 已选商品总件数
    selectedTotal (state, getters) {
      return getters.selectedList.reduce((p, c) => p + c.count, 0)
    },
    // 已选商品总金额
    selectedAmount (state, getters) {
      return (
        getters.selectedList.reduce(
          (p, c) => p + Math.round(c.nowPrice * 100) * c.count,
          0
        ) / 100
      )
    },
    // 是否全选
    isCheckAll (state, getters) {
      return (
        getters.validList.length !== 0 &&
        getters.selectedList.length === getters.validList.length
      )
    }
  },
  mutations: {
    // 加入购物车
    insertCart (state, payload) {
      // 判断当前商品在购物车中是否存在
      const cartindex = state.list.findIndex(
        (item) => item.skuId === payload.skuId
      )
      if (cartindex > -1) {
        payload.count += state.list[cartindex].count
        state.list.splice(cartindex, 1)
      }
      state.list.unshift(payload)
    },
    // 修改购物车商品的信息
    updateCart (state, payload) {
      const cat = state.list.find((item) => item.skuId === payload.skuId)
      for (const item in payload) {
        if (
          payload[item] !== undefined &&
          payload[item] !== '' &&
          payload[item] !== null
        ) {
          cat[item] = payload[item]
        }
      }
    },
    // 删除购物车商品
    deleteCart (state, skuId) {
      const index = state.list.findIndex((item) => item.skuId === skuId)
      state.list.splice(index, 1)
    },
    // 设置购物车
    setCart (state, payload) {
      // payload 为空数组，清空。为又值数组，设置。
      state.list = payload
    }
  },
  actions: {
    // 合并购物车
    async mergeCart (ctx) {
      // 准备合并的参数
      const cartList = ctx.state.list.map((goods) => {
        return {
          skuId: goods.skuId,
          selected: goods.selected,
          count: goods.count
        }
      })
      await mergeCartapi(cartList)
      // 合并成功，清空本地购物车
      ctx.commit('setCart', [])
    },
    // 修改规格
    updateCartSku (ctx, { oldSkuId, newSku }) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          // 已经登陆
          const oldgood = ctx.state.list.find((item) => item.skuId === oldSkuId)
          deleteCartapi([oldSkuId])
            .then(() => {
              return insertCart({ skuId: newSku.skuId, count: oldgood.count })
            })
            .then(() => {
              return findCartapi()
            })
            .then((res) => {
              ctx.commit('setCart', res.result)
              resolve()
            })
        } else {
          // 未登录
          // 1. 找出旧的商品信息
          // 2. 删除旧商品数据
          // 3. 根据新的sku信息和旧的商品信息，合并成一条新的购物车商品数据
          // 4. 添加新的商品
          const oldGoods = ctx.state.list.find(
            (item) => item.skuId === oldSkuId
          )
          ctx.commit('deleteCart', oldSkuId)
          const {
            skuId,
            price: nowPrice,
            specsText: attrsText,
            inventory: stock
          } = newSku
          const newGoods = { ...oldGoods, skuId, nowPrice, attrsText, stock }
          ctx.commit('insertCart', newGoods)
          resolve()
        }
      })
    },
    // 批量删除
    batchDeleteCart (ctx, isClear) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          // 已登录
          const arr = ctx.getters[
            isClear ? 'selectedList' : 'invalidList'
          ].forEach((item) => item.skuId)
          deleteCartapi(arr)
            .then(() => {
              return findCartapi()
            })
            .then((data) => {
              // console.log(data.result)
              ctx.commit('setCart', data.result)
              resolve()
            })
        } else {
          // 未登录
          // 找出选中的商品列表，遍历调用删除的mutations
          // isClear 未 true  删除失效商品列表，否则事选中的商品列表
          ctx.getters[isClear ? 'selectedList' : 'invalidList'].forEach(
            (item) => {
              ctx.commit('deleteCart', item.skuId)
            }
          )
          resolve()
        }
      })
    },
    // 全选与取消全选
    checkAllCart (ctx, selected) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          // 已登录
          const arr = ctx.getters.validList.map((item) => item.skuId)
          checkAllCartapi({ selected, arr })
            .then(() => {
              return findCartapi()
            })
            .then((res) => {
              ctx.commit('setCart', res.result)
              resolve()
            })
        } else {
          // 未登录
          ctx.getters.validList.forEach((goods) => {
            ctx.commit('updateCart', { skuId: goods.skuId, selected })
          })
          resolve()
        }
      })
    },
    // 修改购物车（选中状态，数量）
    updateCart (ctx, payload) {
      // payload 需要：必需有skuId  可能：selected  count
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          // 已登录
          updateCartapi(payload)
            .then(() => {
              return findCartapi()
            })
            .then((res) => {
              ctx.commit('setCart', res.result)
            })
        } else {
          // 未登录
          ctx.commit('updateCart', payload)
          resolve()
        }
      })
    },
    // 删除购物车
    deleteCart (ctx, payload) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          // 已登录
          deleteCartapi([payload])
            .then(() => {
              return findCartapi()
            })
            .then((data) => {
              ctx.commit('setCart', data.result)
              resolve()
            })
        } else {
          // 未登录
          // 单条删除 payload 现在  就是skuId
          ctx.commit('deleteCart', payload)
          resolve()
        }
      })
    },
    // 加入购物车
    insertCart (ctx, payload) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          insertCart({ skuId: payload.skuId, count: payload.count }).then(
            () => {
              findCartapi().then((res) => {
                // console.log(res.result)
                ctx.commit('setCart', res.result)
                resolve()
              })
            }
          )
          // 已登录
        } else {
          // 未登录
          ctx.commit('insertCart', payload)
          resolve()
        }
      })
    },
    // 获取商品列表
    findCart (ctx) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          // 已登录
          findCartapi().then((data) => {
            ctx.commit('setCart', data.result)
            resolve()
          })
        } else {
          // 未登录
          // 对购物车的所有商品重新获取信息
          // console.log(ctx.state.list)
          const p = ctx.state.list.map((item) => {
            return getNewCartGoods(item.skuId)
          })
          Promise.all(p).then((reslist) => {
            reslist.forEach((data, i) => {
              ctx.commit('updateCart', {
                skuId: ctx.state.list[i].skuId,
                ...data.result
              })
            })
          })
          resolve()
        }
      })
    }
  }
}
